 
package c.x.jy.service.aspect;

import java.lang.reflect.Method;

import c.x.jy.service.redis.RedisConstant;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.reflect.MethodSignature;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;

import c.x.jy.common.annotation.DelCache;
import c.x.jy.common.exception.RRException;
import c.x.jy.common.utils.GetClassinfo;
import c.x.jy.service.redis.RedisUtils;
import c.x.jy.service.utils.SpringContextUtils;
import lombok.extern.slf4j.Slf4j;

/**
 * Redis切面处理类
 *
 */
@Slf4j
@Aspect
@Configuration
public class RedisAspect {
  //  private Logger logger = LoggerFactory.getLogger(getClass());
    //是否开启redis缓存  true开启   false关闭
    @Value("${spring.redis.open: false}")
    private boolean open;
 
  //  @Around("execution(* c.x.jy.util.RedisUtils.*(..))")
    public Object around(ProceedingJoinPoint point) throws Throwable {
        Object result = null;
        if(open){
            try{
            
                result = point.proceed();
            }catch (Exception e){
                log.error("redis error", e);
                throw new RRException("Redis服务异常");
            }
        }
        return result;
    }
    
    
    /**
     *    redis 批量删除方法
     * @param point
     * @return
     * @throws Throwable
     */
  	@Around("@annotation(c.x.jy.common.annotation.DelCache)")
  	public Object beforeMethod(ProceedingJoinPoint  point)   {
     Object result =null;
		try {
			result = point.proceed();

		} catch (Throwable e) {
			e.printStackTrace();

			throw new RRException(e.getMessage());
		}finally {

		}


		try {
  			MethodSignature ms = (MethodSignature) point.getSignature();
  			Method targetMethod = point.getTarget().getClass().getMethod(ms.getName(), ms.getParameterTypes());
  			DelCache ann = targetMethod.getAnnotation(DelCache.class);
  			String[] args=new String[2];
  			args[0]= ann.value()[0] ;
  			if(ann.value().length<2) {
  				args[1]="*"; 
  			}else {
  				args[1]=ann.value()[1];
  			}
  			GetClassinfo.invoke(SpringContextUtils.getBean(RedisUtils.class), "del",new  Class[] { String.class,String.class},args);
  		} catch (Exception e) {
  			e.printStackTrace();
  		}
  		
  	return  result;
  	}
    
}
